package itbour.onetouchshow.activity.video.videoplay;


import android.app.Dialog;
import android.content.IntentFilter;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.OneToucDialog;
import com.google.gson.Gson;
import com.umeng.analytics.MobclickAgent;
import com.xiao.nicevideoplayer.NiceVideoPlayer;

import org.greenrobot.eventbus.EventBus;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import itbour.onetouchshow.App;
import itbour.onetouchshow.R;
import itbour.onetouchshow.activity.login.LoginActivity;
import itbour.onetouchshow.activity.userinfo.VipDetailActivity;
import itbour.onetouchshow.activity.version1_6.MakeActivityV1_6;
import itbour.onetouchshow.activity.web.CommWebActivity;
import itbour.onetouchshow.base.BaseIJKPlayActivity;
import itbour.onetouchshow.bean.DesignListBean;
import itbour.onetouchshow.bean.ModelVideoBean;
import itbour.onetouchshow.bean.UserDetailInfoBean;
import itbour.onetouchshow.bean.VideoBean;
import itbour.onetouchshow.bean.VipInfoBean;
import itbour.onetouchshow.bean.eventbus.UpdateUserAction;
import itbour.onetouchshow.bean.user.UserMakeTag;
import itbour.onetouchshow.constants.AppConst;
import itbour.onetouchshow.constants.platform.WorkPlatform;
import itbour.onetouchshow.listener.OnMultiClickListener;
import itbour.onetouchshow.utils.BroadcastAction;
import itbour.onetouchshow.utils.FinshBroadcast;
import itbour.onetouchshow.utils.JumpUtils;
import itbour.onetouchshow.utils.L_;
import itbour.onetouchshow.utils.T_;
import itbour.onetouchshow.utils.UIUtils;

import static itbour.onetouchshow.bean.eventbus.UpdateUserAction.TYPE_CREATEWORK;


/**
 * MVPPlugin
 * 邮箱 784787081@qq.com
 */

public class VideoplayActivity extends BaseIJKPlayActivity<VideoplayContract.View, VideoplayPresenter> implements VideoplayContract.View {

    @BindView(R.id.id_cusvideoplay)
    NiceVideoPlayer landLayoutVideo;
    @BindView(R.id.id_tv_mack)
    TextView idTvMack;
    @BindView(R.id.id_ck_collect)
    CheckBox ckCollect;
    @BindView(R.id.id_user_count)
    TextView userCount;
    @BindView(R.id.id_video_name)
    TextView videoNameTv;
    @BindView(R.id.id_tv_count)
    TextView idTvCount;

    @BindView(R.id.id_tv_xiumicount)
    TextView tvXiumicount;
    @BindView(R.id.id_image_count)
    TextView idImageCount;
    @BindView(R.id.id_video_count)
    TextView idVideoCount;
    @BindView(R.id.id_ly_video_count)
    LinearLayout lyVideoCount;
    @BindView(R.id.id_ly_image_count)
    LinearLayout lyImageCount;
    @BindView(R.id.iv_vip_template)
    ImageView iv_vip_template;
    @BindView(R.id.tv_times)
    TextView tvTimes;


    private VideoBean videoItem;
    private ModelVideoBean modelVideoBean;
    private boolean initsuccess = true;
    //这是用于退出三段式逻辑的广播
    private FinshBroadcast quitThreeLogicBroadcast = new FinshBroadcast();


    @Override
    public void loadSucceed(String result) {

    }

    @Override
    public void loadFaild(String error) {
        if (error.equals("该模板已下架")) {
            T_.customStylesToast(error);
            finish();
        }
        initsuccess = false;
        showEmptyView(R.mipmap.icon_no_network, "请检查网络");
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_new_video_play;
    }

    @Override
    protected void initTitle() {
        super.initTitle();
        setTitleText("视频详情");
        registerExitReceiver();
        EventBus.getDefault().register(this);
        //requestPermissions();
    }

    @Override
    public void dataEvent(UserMakeTag userMakeTag) {
        if (userMakeTag.equals(UserMakeTag.BUYVIP)) {
            toastMessage();
        }

    }

    @Override
    protected void afterCreate(Bundle savedInstanceState) {
        //设置缩略图
        super.afterCreate(savedInstanceState);
        showLoadingView();
        Bundle extras = getIntent().getExtras();
        if (extras != null) {
            String moudleresult = extras.getString(JumpUtils.VIDEOACTIVITY_TAG);
            loadPageInfoSuccess(moudleresult);
        }

        idTvMack.setOnClickListener(new OnMultiClickListener() {
            @Override
            public void onMultiClick(View v) {
                if (App.isLogin()) {
                    // throw new NullPointerException("异常处理");
                    // mPresenter.loadUserDetailInfo();
                    //VIP模板  用户不是VIP
                    //new Throwable(new NullPointerException(""));
                    showProgressDialogWithText("");
                    mPresenter.goToMack(modelVideoBean, 1);
                } else {
                    openActivity(LoginActivity.class);
                }
            }
        });


    }

    /**
     * 不是尊享会员弹出提示
     */
    public void showVipDialog() {
        new OneToucDialog.Builder(this)
                .content("该模板仅限尊享会员使用,开通" /*+ "\n"*/ + "尊享会员获取更多特权及服务。")
                .positiveText("去查看").onPositive(new OneToucDialog.SingleButtonCallback() {
            @Override
            public void onClick(OneToucDialog dialog, DialogAction which) {
                mPresenter.getVipPageInfo();
                // toastMessage();
                // showCustomVipDialog();

            }
        })
                .negativeText("取消").onNegative(new OneToucDialog.SingleButtonCallback() {
            @Override
            public void onClick(OneToucDialog dialog, DialogAction which) {
                //  Log.e("TAH", "点击确定");
            }
        }).setType(OneToucDialog.Builder.ONE_TOUCH_TYPE)
                .cancelable(false).setmWidth(AppConst.APP_DIALOG_WIDTH)
                .show();
    }

    @Override
    protected int videoHeight() {
        return UIUtils.getHForScan(videoItem.getW(), videoItem.getH());
    }

    @Override
    public void loadPageInfoSuccess(String result) {
        L_.e("loadPageInfoSuccess" + result);
        showContentView();
        modelVideoBean = new Gson().fromJson(result, ModelVideoBean.class);
        videoItem = modelVideoBean.getVideo();
        L_.e("modelVideoBean.getId" + modelVideoBean.getId());
        if (App.isLogin()) {
            mPresenter.loadThisIsCollect(modelVideoBean);
        }
        if (modelVideoBean.getVideo() == null) return;
        onStartPlay(modelVideoBean.getVideo().getVideoUrl(), modelVideoBean.getName());
        videoNameTv.setText(modelVideoBean.getName());
        idTvMack.setEnabled(true);
        userCount.setText(modelVideoBean.getUseCounts() + "人在使用");
        idTvCount.setText(modelVideoBean.getReplaceTextCnt() + "");

        tvXiumicount.setText(Integer.valueOf(modelVideoBean.getXmPrice()) / 100 + "秀米");

        if (modelVideoBean.getReplaceImageCnt() == 0) {
            lyImageCount.setVisibility(View.GONE);
        }

        if (modelVideoBean.getReplaceVideoCnt() == 0) {
            lyVideoCount.setVisibility(View.GONE);
        }

        if (modelVideoBean.isVip()) {
            iv_vip_template.setVisibility(View.VISIBLE);
        }
        idImageCount.setText(modelVideoBean.getReplaceImageCnt() + "");
        idVideoCount.setText(modelVideoBean.getReplaceVideoCnt() + "");
        tvTimes.setText(((int) modelVideoBean.getVideo().getDuration()) + "s");
    }

    /**
     * 通知个人中心状态刷新
     */
    public void freshMeMessage() {
        UpdateUserAction updateUserAction = new UpdateUserAction();
        updateUserAction.setSubType(TYPE_CREATEWORK);
        EventBus.getDefault().post(updateUserAction);
    }

    /**
     * 显示Vip开通成功弹框  自己消失
     */
    private void toastMessage() {

        freshMeMessage();

        //LayoutInflater的作用：对于一个没有被载入或者想要动态载入的界面，都需要LayoutInflater.inflate()来载入，LayoutInflater是用来找res/layout/下的xml布局文件，并且实例化
        LayoutInflater inflater = getLayoutInflater();//调用Activity的getLayoutInflater()
        View view = inflater.inflate(R.layout.custom_vip_dialog, null); //加載layout下的布局
        ImageView imageView = view.findViewById(R.id.id_ig_dia_icon);
        ViewGroup.LayoutParams layoutParams = imageView.getLayoutParams();
        Toast toast = new Toast(getApplicationContext());
        int width = UIUtils.WHD()[0] / 6 * 5;
        int height = width * 2 / 3;
        layoutParams.width = width;
        layoutParams.height = height;
        toast.setGravity(Gravity.CENTER, 0, 0);//setGravity用来设置Toast显示的位置，相当于xml中的android:gravity或android:layout_gravity
        // toast.setDuration(Toast.LENGTH_LONG);//setDuration方法：设置持续时间，以毫秒为单位。该方法是设置补间动画时间长度的主要方法
        toast.setView(view); //添加视图文件
        toast.show();
        /**
         *  设置背景模糊     模糊度
         */
        backgroundAlpha(0.5f);
        UIUtils.getHandler().postDelayed(new Runnable() {
            @Override
            public void run() {
                toast.cancel();
                backgroundAlpha(1.0f);
            }
        }, 2000);
    }

    public void showCustomVipDialog() {
        Dialog dia = new Dialog(this, R.style.edit_AlertDialog_style);
        dia.setContentView(R.layout.custom_vip_dialog);
        dia.show();
        dia.setCanceledOnTouchOutside(false); // Sets whether this dialog is
        dia.setCancelable(false);
        Window w = dia.getWindow();
        WindowManager.LayoutParams lp = w.getAttributes();
        if (dia != null) {
            int width = UIUtils.WHD()[0] / 6 * 5;
            int height = width * 2 / 3;
            dia.getWindow().setLayout(width, height);
        }
        dia.onWindowAttributesChanged(lp);

        UIUtils.getHandler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (dia != null && dia.isShowing()) {
                    dia.dismiss();
                }
            }
        }, 500);

    }

    @Override
    public void loadProductPreviewData(String result) {
//
    }

    @Override
    public void loadVipInfoSuccess(String result) {
        // 当appHomeVipUrl有值时跳转到Web页面 否则使用本地页面
        VipInfoBean vipInfoBean = new Gson().fromJson(result, VipInfoBean.class);
        //InchingDataSingleCase.INSTANCE.setVipInfoBean(vipInfoBean);
        if (vipInfoBean != null && !TextUtils.isEmpty(vipInfoBean.getAppHomeVipUrl())) {
            Bundle bundle = new Bundle();
            bundle.putString(AppConst.WEBTYPE, AppConst.APP_VIP_WEB_PAY);
            bundle.putString(AppConst.WEBURL, vipInfoBean.getAppHomeVipUrl());
            openActivity(CommWebActivity.class, bundle);

        } else {
            if (vipInfoBean == null || vipInfoBean.getIntroduceInfo() == null) return;
            startActivity(VipDetailActivity.getLaunchIntent(VideoplayActivity.this, vipInfoBean.getIntroduceInfo(), VipDetailActivity.TAG_PLAY));
        }
    }

    @Override
    public void loadVipInfoFail(String result) {

    }

    /**
     * 获取用户是否是vip
     *
     * @param result
     */
    @Override
    public void loaduserDetailSuccess(String result) {
        UserDetailInfoBean userDetailInfoBean = new Gson().fromJson(result, UserDetailInfoBean.class);
        if (userDetailInfoBean == null) {
            return;
        }
        if (modelVideoBean.isVip() && !userDetailInfoBean.getIsVip()) {
            showVipDialog();
        } else {
            mPresenter.goToMack(modelVideoBean, 1);
        }

    }

    @Override
    public void loadNewDocPreviewSuccess(String result) {

    }

    @Override
    protected NiceVideoPlayer getmNiceVideoPlayer() {
        return landLayoutVideo;
    }

    @OnClick({R.id.id_ck_collect})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.id_ck_collect:
                if (App.isLogin()) {
                    Boolean isCollect = ckCollect.isSelected();
                    if (modelVideoBean != null) {
                        mPresenter.collectOrCancalCollectThisModel(isCollect, modelVideoBean.getId());
                    }
                } else {
                    openActivity(LoginActivity.class);
                }
                break;
            default:
        }
    }

    @Override
    public void loadPreviewBgSuccess(String result) {

    }

    @Override
    public void loadMoudelSuccess(String result) {
        Bundle bundle = new Bundle();
        bundle.putString("module", result);
        bundle.putString(WorkPlatform.TYPE, WorkPlatform.MOUDLE);
        openActivity(MakeActivityV1_6.class, bundle);
        dismissProgressDialog();
    }

    @Override
    public void isCollect() {
        ckCollect.setSelected(true);
    }

    @Override
    public void unCollect() {
        ckCollect.setSelected(false);
    }

    @Override
    public void nowFragmentVisable(DesignListBean.ListBean listBean) {

    }

    @Override
    public void collectSuccess(String text) {

    }

    @Override
    public void collectFaild() {

    }

    //onCreate调用
    private void registerExitReceiver() {
        IntentFilter exitFilter = new IntentFilter();
        exitFilter.addAction(BroadcastAction.EXIT_THREE_LOGIC);
        registerReceiver(quitThreeLogicBroadcast, exitFilter);
    }

    //onDestory反注册
    private void unRegisterExitReceiver() {
        unregisterReceiver(quitThreeLogicBroadcast);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unRegisterExitReceiver();
        EventBus.getDefault().unregister(this);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("p2-视频模板详情页"); //统计页面(仅有Activity的应用中SDK自动调用，不需要单独写。"SplashScreen"为页面名称，可自定义)
        MobclickAgent.onResume(this);          //统计时长
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("p2-视频模板详情页"); // （仅有Activity的应用中SDK自动调用，不需要单独写）保证 onPageEnd 在onPause 之前调用,因为 onPause 中会保存信息。"SplashScreen"为页面名称，可自定义
        MobclickAgent.onPause(this);
    }

}
